<template>
    <div class="map-blk">
        <!-- <div class="switch-map">
			<p :class="{active:mapType=='amap'}" @click="switchMap('amap')">地图</p>
			<p :class="{active:mapType=='bigmap'}" @click="switchMap('bigmap')">混合</p>
		</div> -->
        <div id="map" class="map" v-show="mapType == 'amap'"></div>
        <div id="bigmap" class="map" v-show="mapType == 'bigmap'"></div>
        <div id="map" class="map"></div>
        <el-dialog
            title="报警处置"
            v-if="handleModalVisibleSingle"
            :visible.sync="handleModalVisibleSingle"
            :width="500 * scale + 'px'"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
            @open="openHandleModal(activeAlarm)"
            @close="closeHandleAlarm(activeAlarm, 'modalClose')"
        >
            <Handle
                :ref="'handle' + (activeAlarm && activeAlarm.id)"
                :isAutoClose="true"
                :scale="scale"
                :activeData="activeAlarm"
                :activeDevice="alarmDevices[0]"
                @success="handleSuccessAction(activeAlarm)"
                @fail="handling = false"
                @submitting="handling = true"
                @cancel="closeHandleAlarm(activeAlarm, 'cancel')"
                @autoClose="closeHandleAlarm(activeAlarm, 'autoClose')"
            >
            </Handle>
            <div slot="footer">
                <el-button
                    type="cancel"
                    @click="showMonitor"
                    v-if="alarmDevices[0] && alarmDevices[0].productId == 6002"
                    >鹰眼e通</el-button
                >
                <el-button type="cancel" @click="cancelHandle(activeAlarm)">取消</el-button>
                <el-button
                    type="primary"
                    :loading="handling"
                    @click="submitHandleAction(activeAlarm)"
                    :disabled="!$store.getters.hasEditPermission"
                    >处置</el-button
                >
            </div>
        </el-dialog>
        <!-- 设备详情 start -->
        <el-dialog
            v-if="detailModalVisible"
            title="设备详情"
            :visible.sync="detailModalVisible"
            :width="1000 * scale + 'px'"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
            append-to-body
        >
            <DeviceDetail
                ref="detail"
                :rfid="alarmDevice.rfid"
                :id="alarmDevice.id"
                :productId="alarmDevice.productId"
                :classify="alarmDevice.deviceClassify"
                :number="alarmDevice.number"
                :scale="scale"
                @cancel="detailModalVisible = false"
            >
            </DeviceDetail>
        </el-dialog>
        <!-- 设备详情 end -->
    </div>
</template>
<script>
import { mapState } from "vuex"
import AMap from "AMap"
import FirmDetail from "@/components/iot/FirmDetail.vue"
import Handle from "@/components/HandleAlarm.vue"
import DeviceDetail from "@/components/device/DeviceDetail.vue"
let map
let bigmap
let markers = []
let alarmMarker = {}
let socket = null
const alarmAudio = require("@/assets/audio/620.wav")
let alarmTimer = null
// let deviceIcon = require('@/assets/images/icon-camera')
export default {
    name: "Map",
    props: {
        dataList: {
            type: Array,
            default() {
                return []
            },
        },
    },
    data() {
        return {
            type: this.$route.query.type || "fireControl",
            textLayer: null,
            dataSet: null,
            animationLayer: null,
            loading: false,
            firmList: [],
            firmId: "",
            firmTitle: "",
            firmModalVisible: false,

            handleModalVisible: {},
            handleModalVisibleSingle: false,
            handling: false,
            // activeAlarm: null,
            activeMarkerId: "",
            audio: null,
            isSoundPlaying: false,
            alarmDevice: null,
            detailModalVisible: false,
            mapType: "amap",
            activeAlarms: [],
            alarmDevices: [],
            deviceList: [],
            deviceMarkers: {},
        }
    },
    watch: {
        dataList(newVal) {
            // console.log('map data change')
            // this.createMarkers()
        },
    },
    components: {
        FirmDetail,
        Handle,
        DeviceDetail,
    },
    computed: {
        ...mapState(["scale"]),
        // notificationType () {
        deviceClassify() {
            let typeId = this.config.typeMap[this.type] == 100 ? "" : this.config.typeMap[this.type]
            return typeId || "0"
        },
        activeAlarm() {
            if (this.activeAlarms.length > 0) {
                return this.activeAlarms[0]
            }
            return null
        },
    },

    created() {
        this.openSocket()
    },
    mounted() {
        this.initMap()
        this.getMapData()
        // this.playSound()
        // setTimeout(()=>{
        // 	this.playSound()
        // },2000)
        // setTimeout(()=>{
        // 	this.playSound()
        // },4000)
        // setTimeout(()=>{
        // 	this.playSound()
        // },6000)
        // setTimeout(()=>{
        // 	this.playSound()
        // },8000)
        // setTimeout(()=>{
        // 	this.showAlarmInMap({number:987456321 ,lon:119.19056,lat:36.694235,notificationType:1,alarmId:'fdba6b5e-f1fb-48fd-b995-57d08546b195'})
        // },5000)
        // setTimeout(()=>{
        // 	this.showAlarmInMap({number: 123,lon:119.122356,lat:36.713929,notificationType:0})
        // },100000)
    },
    methods: {
        addMarker(item, isAlarm = false) {
            let point = new AMap.LngLat(item.lon, item.lat)
            let marker = new AMap.Marker({ map: map, position: point })
            let markerContent = `<div class="map-device-icon ${
                isAlarm ? "alarm" : ""
            }"><i class="iconfont icon-monitor-camera"></i></div>`
            marker.setContent(markerContent)
            marker.setExtData(item)
            var text = new AMap.Text({
                text: item.name,
                position: [item.lon, item.lat],
            })
            text.setMap(map)
            return marker
        },
        getMapData() {
            this.$get("/fireFightingIOT/device/getOrgBrightKitchenDevice").then((res) => {
                this.deviceList = res.data
                let deviceMarkers = []
                this.deviceList.forEach((item) => {
                    let marker = this.addMarker(item)
                    this.deviceMarkers["marker" + item.number] = marker
                    deviceMarkers.push(marker)
                })
                map.setFitView(deviceMarkers)
            })
        },
        openHandleModal(item) {
            // console.log('openHandleModal',item)
        },
        closeHandleAlarm(item, type) {
            this.handleModalVisible[item.id] = false
            ;(this.handleModalVisibleSingle = false), this.removeAlarmDevice(item)
            // console.log('closeHandleAlarm',type)
        },

        switchMap(type) {
            if (this.mapType == type) return
            this.mapType = type

            this.$nextTick(() => {
                if (type == "amap") {
                    if (!map) {
                        this.initMap()
                    }
                } else {
                    if (!bigmap) {
                        this.initBigMap()
                    }
                }
            })
        },
        closeDoor() {
            this.$refs.handle.closeDoor()
        },
        onDoorClosed() {
            //
        },
        // 播放险情警报音频
        playSound() {
            if (!this.audio) {
                this.audio = document.createElement("audio")
                //是否进行预加载
                this.audio.preload = "auto"
                this.audio.autoplay = false
                //是否显示隐藏按钮
                this.audio.controls = true
                this.audio.hidden = true
                //绑定音乐结束事件，当音乐播放完成后，将会触发playEndedHandler方法
                this.audio.addEventListener("ended", this.playEndedHandler, false)
                this.audio.addEventListener(
                    "error",
                    () => {
                        console.log("error")
                        this.audio.play()
                    },
                    false
                )
                this.audio.addEventListener(
                    "canplay",
                    () => {
                        this.audio.play()
                        // console.log('正在播放->'+this.audio.src)
                    },
                    false
                )
                document.body.appendChild(this.audio)
            }

            // if(this.soundList.length==0) return
            // var soundItem = this.soundList[0]
            this.audio.src = alarmAudio
            this.isSoundPlaying = true
        },
        // 监听每个音频播放完毕
        playEndedHandler() {
            // console.log('playEndedHandler')
            this.isSoundPlaying = false
        },
        getAlarmDetail(id, cbk) {
            this.$get("/fireFightingIOT/historicalAlarmInfo/detail", {
                id: id,
            }).then(
                (res) => {
                    let thisData = res.data
                    cbk && cbk(thisData)
                },
                (err) => {
                    //
                }
            )
        },
        showMonitor() {
            this.detailModalVisible = true
        },

        cancelHandle(item) {
            this.closeHandleAlarm(item)
        },
        handleAlarmAction(e) {
            let extData = e.target.getExtData() || e.target.getAttribution()
            this.doHandleAlarm(extData)
        },
        doHandleAlarm(extData, cbk) {
            this.handleModalVisibleSingle = false
            this.activeAlarms = []
            this.alarmDevices = []
            // console.log('doHandleAlarm',extData)
            // console.log(this.activeAlarms)
            // if(this.activeAlarms.length>=3) return
            let alarmId = extData.alarmId
            // console.log('alarmId',alarmId)
            this.activeMarkerId = "alarm" + extData.number
            // console.log('activeMarkerId',this.activeMarkerId)
            this.getAlarmDetail(alarmId, (data) => {
                // console.log('getAlarmDetail',data)
                // this.activeAlarm = data
                // let isExsit = this.activeAlarms.filter(item=>{
                // 	return item.id == data.id
                // }).length>0
                // if(!isExsit){
                this.activeAlarms.push(data)

                // }

                this.getDeviceDetail(data.deviceClassify, data.number, (deviceData) => {
                    // console.log('getDeviceDetail',deviceData)
                    this.alarmDevices.push(deviceData)
                    // console.log('alarmDevices',this.alarmDevices)
                    this.$nextTick(() => {
                        this.$set(this.handleModalVisible, data.id, true)
                        this.handleModalVisibleSingle = true
                        // console.log('this.handleModalVisible',this.handleModalVisible)
                    })
                })
                cbk && cbk()
            })
        },
        submitHandleAction(item) {
            this.$refs["handle" + item.id][0].submitAction()
        },
        handleSuccessAction(alarmDevice) {
            // this.alarmDevice = null
            this.handling = false
            alarmMarker["alarm" + alarmDevice.number][1].remove()
            this.closeHandleAlarm(alarmDevice)
            // map.remove(alarmMarker[this.activeMarkerId])
        },
        removeAlarmDevice(alarmDevice) {
            // console.log('removeAlarmDevice')
            let index = 0
            for (let i = 0; i < this.activeAlarms.length; i++) {
                if (alarmDevice.id == this.activeAlarms[i].id) {
                    index = i
                    break
                }
            }
            this.activeAlarms.splice(index, 1)
            this.alarmDevices.splice(index, 1)
            // console.log(index,this.activeAlarms)
        },
        getDeviceDetail(deviceClassify, number, cbk) {
            this.$get("/fireFightingIOT/device/detail", {
                deviceClassify: deviceClassify,
                number: number,
                id: "",
            }).then(
                (res) => {
                    this.alarmDevice = res.data
                    cbk && cbk(res.data)
                },
                (err) => {
                    //
                }
            )
        },
        openSocket() {
            socket = io(this.config.socketUrl, { path: "/socket.io" })
            // uid 可以为网站用户的uid，作为例子这里用session_id代替
            let uid = "1111"
            // 当socket连接后发送登录请求
            socket.on("connect", function() {
                console.log("connect")
            })
            // 当服务端推送来消息时触发
            socket.on("new_msg", (msg) => {
                // console.log('new_msg');
                let dataArr = msg.split(",")
                let pointData = {}
                dataArr.forEach((item) => {
                    let temp = item.split("=")
                    pointData[temp[0]] = temp[1]
                })
                if (
                    (this.deviceClassify == "0" ||
                        pointData.deviceClassify == this.deviceClassify) &&
                    pointData.alarmId.length > 0
                ) {
                    this.$get("/fireFightingIOT/historicalAlarmInfo/isAlarm", {
                        alarmId: pointData.alarmId,
                    }).then(
                        (res) => {
                            if (res.data.flag) {
                                this.showAlarmInMap(pointData)
                                this.$emit("alarm")
                            }
                        },
                        (err) => {
                            //
                        }
                    )
                }

                // if(pointData.lng && pointData.lat){
                // 	this.$emit('alarm')
                // }
            })
        },
        showAlarmInMap(pointData) {
            let lng = pointData.lon
            let lat = pointData.lat
            if (!lng || !lat) return
            let number = pointData.number
            let alarmId = pointData.alarmId
            let thisDevice = this.deviceList.find((item) => item.number == number)
            thisDevice.alarmId = alarmId
            if (this.deviceMarkers["marker" + number]) {
                map.remove(this.deviceMarkers["marker" + number])
            }
            if (!this.isSoundPlaying) {
                this.playSound()
            }
            // if(!!alarmMarker['alarm'+pointData.number]){
            // 	return
            // }
            if (!alarmMarker["alarm" + pointData.number]) {
                alarmMarker["alarm" + pointData.number] = []
            }
            this.doHandleAlarm(pointData)
            if (this.mapStyle == "bigmap") {
                if (!BM) return
                let warnIcon = BM.divIcon({
                    html: '<div class="unit-warn-icon"><i class="play-pulse"></i></div>',
                })
                let bigmapMarker = BM.marker([lat, lng], {
                    icon: warnIcon,
                    attribution: pointData,
                }).addTo(bigmap)
                bigmapMarker.on("click", this.handleAlarmAction)
                alarmMarker["alarm" + pointData.number][0] = bigmapMarker
            } else {
                let marker = this.addMarker(thisDevice, true)
                marker.on("click", this.handleAlarmAction)
                alarmMarker["alarm" + pointData.number][1] = marker
                let temp = Object.values(alarmMarker)
                let alarmMarkers = temp.map((item) => item[1])
                map.setFitView(alarmMarkers)
            }
            /* let point = new AMap.LngLat(lng, lat);
			// let unitWarnIcon = new AMap.Icon({
			// 	size: new AMap.Size(30, 38),
			// 	image: require('../../assets/images/iot/unitWarn.png'),
			// 	imageSize: new AMap.Size(30, 38),
			// 	imageOffset: new AMap.Pixel(0, 0)
			// });
			// let marker = new AMap.Marker({ map: map, position: point, icon: unitWarnIcon });  // 创建标注
			// let warnIcon = require('../../assets/images/iot/unitWarn.png')
			// let markerContent = `<div class="uni-warn-icon play-drop"><img src="${warnIcon}" alt=""></div>`
			let marker = new AMap.Marker({ map: map, position: point});
			let markerContent = `<div class="unit-warn-icon"><i class="play-pulse"></i></div>`
			marker.setContent(markerContent)
			marker.setExtData(pointData)
			marker.on('click', this.handleAlarmAction);
			alarmMarker['alarm'+pointData.number] = marker
			let alarmMarkers = Object.values(alarmMarker)
			map.setFitView(alarmMarkers);
			
			// map.setZoomAndCenter(17, point);
			// cluster = new AMap.MarkerClusterer(map, markers, {gridSize: 80});*/
        },
        changeFirm(value) {
            this.firmId = value
            this.firmModalVisible = true
            let selectedFirm = this.firmList.filter((item) => {
                return item.id == value
            })
            this.firmTitle = selectedFirm[0].name
            let lng = selectedFirm[0].lon
            let lat = selectedFirm[0].lat
            if (lng && lat) {
                let point = new AMap.LngLat(lng, lat)
                let marker = new AMap.Marker({ map: map, position: point })
                marker.setLabel({
                    offset: new AMap.Pixel(0, 25),
                    content: "<div class='marker-title'>" + this.firmTitle + "</div>",
                    direction: "center",
                })
                marker.on("click", () => {
                    this.firmModalVisible = true
                })
                map.setZoomAndCenter(19, point)
            }
        },
        openFirmDetail() {
            // this.$nextTick(()=>{
            // 	this.$refs.firmDetail.getData()
            // })
        },
        remoteMethod(query) {
            this.loading = true
            this.$get("/business/business/businessList", {
                name: query,
            }).then(
                (res) => {
                    this.loading = false
                    this.firmList = res.data
                },
                (err) => {
                    //
                }
            )
        },
        // 创建地图
        createMap() {
            map = new BMap.Map("map", { enableMapClick: false })
            map.setMaxZoom(12)
            map.enableScrollWheelZoom()
            // map.centerAndZoom(new BMap.Point(119.122356,36.713929), 10);
            map.setMapStyleV2({ styleJson: this.config.mapStyle })
            // map.setCity('潍坊市')
        },

        initBigMap() {
            if (!BM) return
            bigmap = BM.map("bigmap", "bigemap.djo9kxg4", {
                crs: BM.CRS.EPSG4326,
                center: [36.05330276489258, 117.01811981201172],
                zoom: 15,
                zoomControl: false,
            })
            // bigmap.fitBounds([[35.6307487487793, 116.04283905029297], [36.47585678100586, 117.99340057373047]]);
        },
        initMap() {
            map = new AMap.Map("map", {
                resizeEnable: true,
                rotateEnable: false,
                pitchEnable: false,
                expandZoomRange: true,
                zooms: [3, 20],
                zoom: 15,
                pitch: 30,
                // rotation: -15,
                // viewMode: '3D', //开启3D视图,默认为关闭
                buildingAnimation: false, //楼块出现是否带动画
                // layers: [new AMap.TileLayer.Satellite()],
                // center: [119.122356,36.713929],
                center: [117.01811981201172, 36.05330276489258],
                mapStyle: "amap://styles/darkblue",
                // mapStyle: 'amap://styles/grey'
            })
            // map.setCity('潍坊市')
        },
        // initMap () {
        // 	map = new AMap.Map('map', {
        // 		resizeEnable: true,
        // 		rotateEnable: true,
        // 		pitchEnable: true,
        // 		expandZoomRange: true,
        // 		zoom: 15,
        // 		pitch: 30,
        // 		// rotation: -15,
        // 		// viewMode: '3D', //开启3D视图,默认为关闭
        // 		buildingAnimation: true, //楼块出现是否带动画
        // 		expandZoomRange: true,
        // 		zooms: [3, 20],
        // 		// center: [119.122356,36.713929],
        // 		mapStyle: 'amap://styles/darkblue'
        // 		// mapStyle: 'amap://styles/grey'
        // 	});
        // 	map.setCity('潍坊市')
        // },
    },
}
</script>
